﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using DateBaseConnectionPool;

namespace TestMySqlConnetPoll
{
    public struct objTableScanAnnal
    {
        public int s_time;
        public int e_time;
        public string strTableE;  //表格名称
        public string UserName;


        public objTableScanAnnal(int s, int e)
        {
            s_time = s;
            e_time = e;
            strTableE = string.Empty;
            UserName = string.Empty;
        }
    }
    public class UserScanTable
    {
        #region 外部变量定义，变量定义 表格浏览记录
        
        //报表浏览记录没有时间列表，都按最近30天多时间列表，没有记录时，返回的是空值.
        private string ScanTableType = "";       //报表浏览类型
        private DateTime ScanTableTime = new DateTime();     //报表浏览的时间，某天的浏览记录
        //浏览记录，以设备号作为键值
        public Dictionary<string, List<objTableScanAnnal>> ValueList = new Dictionary<string, List<objTableScanAnnal>>();
        public bool Ready_ValueList = false;
        public int  ErrorType = 0;       //读取日报表失败标志，0标志未读取获取无错误，非0表示有错误，需要界面提示
        struct scanThreadobj
        {
            public string TableType;
            public DateTime time;
        }

        public void Read_ValueList(string TableType,DateTime time)
        {
            Ready_ValueList = false;
            ErrorType = 0;
            if (ScanTableType != TableType)
            {
                ScanTableType = TableType;
                ValueList.Clear();
            }
            if (ScanTableTime.Year != time.Year || ScanTableTime.Month != time.Month || ScanTableTime.Day != time.Day)
            {
                ScanTableTime = time;
                ValueList.Clear();
            }
            scanThreadobj obj = new scanThreadobj();
            obj.TableType = TableType;
            obj.time = time;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadTableScanValueList), obj);
        }

        #endregion
        #region 表格浏览记录
        private Mutex keyMutex = new Mutex();
        static private int keykey = 0;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ScanType">
        /// 设备浏览记录
        /// 道岔动作电流曲线浏览记录
        /// 报警浏览记录
        /// </param>
        /// <param name="ScanNo">报表名称</param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool InsertTableScanData(string ScanType,string ScanNo, objTableScanAnnal obj)
        {
            bool tmpFlag = false;
            string TableName = "TableScanAnnal";
            int tableType = c_Device.GetUserScanTableType(ScanType) ;
            int tableNo = c_Device.GetUserScanTableNo(ScanType, ScanNo);
            string TableTxt= ScanNo;
            string UserName =MySql.CurrentUserName;
            if (tableType == -1 || tableNo == -1)
            {
                
            }

            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    tmpFlag = false;
                }
                
                if (con != null)
                {
                    StringBuilder InsertStatement = new StringBuilder();
                    InsertStatement.Append(string.Format("insert into {0}(year,month,day,TableType,TableNo,TableName,UserName,s_time,e_time) ", TableName));

                    InsertStatement.Append(" values(?year,?month,?day,?TableType,?TableNo,?TableName,?UserName,?s_time,?e_time)");

                    MySqlCommand InsertCommand = new MySqlCommand(InsertStatement.ToString(), con);

                    InsertCommand.Parameters.Add(new MySqlParameter("?year", MySqlDbType.Int32)).Value = DateTime.Now.Year;
                    InsertCommand.Parameters.Add(new MySqlParameter("?month", MySqlDbType.Byte)).Value = DateTime.Now.Month;
                    InsertCommand.Parameters.Add(new MySqlParameter("?day", MySqlDbType.Byte)).Value = DateTime.Now.Day;

                    InsertCommand.Parameters.Add(new MySqlParameter("?TableType", MySqlDbType.Byte)).Value = (byte)tableType;
                    InsertCommand.Parameters.Add(new MySqlParameter("?TableNo", MySqlDbType.Int16)).Value = (Int16)tableNo;

                    InsertCommand.Parameters.Add(new MySqlParameter("?TableName", MySqlDbType.VarChar)).Value = TableTxt;
                    InsertCommand.Parameters.Add(new MySqlParameter("?UserName", MySqlDbType.VarChar)).Value = UserName;

                    InsertCommand.Parameters.Add(new MySqlParameter("?s_time", MySqlDbType.Int16)).Value = obj.s_time;
                    InsertCommand.Parameters.Add(new MySqlParameter("?e_time", MySqlDbType.Int16)).Value = obj.e_time;

                    try
                    {
                        int k = InsertCommand.ExecuteNonQuery();
                        if (k == 1) tmpFlag = true;        //写入成功
                        else tmpFlag = false;              //写入失败
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                        tmpFlag = false;       //写入失败
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                    }
                }
            }
            return tmpFlag;
        }

        //private void ThreadReadTableScanTimeList(string TableName, byte tableType)
        //{
        //    TableScanAnnalTimeList.Clear();
        //    if (TableName == "") return ;
        //    if (MySql.c != null && MySql.c.State == PoolState.Run)
        //    {
        //        MySqlConnection con = new MySqlConnection();
        //        string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString()+ (MySql.key++).ToString();
        //        try
        //        {
        //            con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
        //        }
        //        catch (MySqlException ex)
        //        {
        //            //写异常日志
        //            tmpFlag = false;
        //        }
        //        if (con != null)
        //        {
        //            StringBuilder SelectStatement = new StringBuilder();

        //            SelectStatement.Append(string.Format("select(year,month,day) from{0} where TableType = {1}", TableName, tableType));

        //            try
        //            {
        //                MySqlCommand selectCommand = new MySqlCommand(SelectStatement.ToString(), con);
        //                selectCommand.CommandTimeout = 120;   //120s操作超时

        //                MySqlDataReader read = selectCommand.ExecuteReader();
        //                while (read.Read())
        //                {
        //                    objDate t = new objDate();
        //                    t.year = read.GetInt32(read.GetOrdinal("year"));
        //                    t.month = read.GetByte(read.GetOrdinal("month"));
        //                    t.day = read.GetByte(read.GetOrdinal("day"));
        //                    if (TableScanAnnalTimeList.Contains(t)) { }
        //                    else TableScanAnnalTimeList.Add(t);     //加入到时间列表里面
        //                }
        //                read.Close();
        //                tmpFlag = true;
        //            }
        //            catch (MySqlException e)
        //            {
        //                //写错误日志
        //                tmpFlag = false;
        //            }
        //            try
        //            {
        //                MySql.c.DisposeConnection(key);
        //            }
        //            catch (MySqlException e)
        //            {
        //                //写错误日志
        //                tmpFlag = false;
        //            }
        //        }
        //    }
        //    return tmpFlag;
        //}

        private void ThreadReadTableScanValueList(object o)
        {
            string TableName = "TableScanAnnal";
            scanThreadobj obj = (scanThreadobj)o;
            objDate date = new objDate();
            date.year = obj.time.Year;
            date.month = (byte)obj.time.Month;
            date.day = (byte)obj.time.Day;
            string TableType = obj.TableType;
            int TableScanType = c_Device.GetUserScanTableType(obj.TableType);
            if (TableScanType == -1)
            {
                ErrorType = 1;
                return;
            }
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorType = 2;
                }
                
                if (con != null)
                {
                    StringBuilder SelectStatement = new StringBuilder();

                    SelectStatement.Append(string.Format("select TableNo,TableName,UserName,s_time,e_time from {0} where year = {1} and month = {2} and day = {3} and  TableType = {4}", TableName, date.year, date.month, date.day, TableScanType));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(SelectStatement.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            objTableScanAnnal t = new objTableScanAnnal();
                            Int16 no = read.GetInt16(read.GetOrdinal("TableNo"));
                            if (!read.IsDBNull(read.GetOrdinal("TableName")))
                            {
                                t.strTableE = read.GetString(read.GetOrdinal("TableName"));
                            }
                            if (!read.IsDBNull(read.GetOrdinal("UserName")))
                            {
                                t.UserName = read.GetString(read.GetOrdinal("UserName"));
                            }
                            t.s_time = read.GetInt32(read.GetOrdinal("s_time"));
                            t.e_time = read.GetInt32(read.GetOrdinal("e_time"));
                            string KeyString = c_Device.GetUserScanTableName(TableScanType, no);
                            if (KeyString == "") KeyString = t.strTableE;
                            if (ValueList.ContainsKey(KeyString))
                            {
                                ValueList[KeyString].Add(t);
                            }
                            else
                            {
                                List<objTableScanAnnal> k = new List<objTableScanAnnal>();
                                k.Add(t);
                                ValueList.Add(KeyString, k);
                            }
                        }
                        read.Close();
                        Ready_ValueList = true;
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorType = 3;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorType = 4;
                    }
                }
                else ErrorType = 6;
            }
            else ErrorType = 7;
        }
        #endregion
    }
}
